<?php

namespace App\Containers\AppSection\File\Tasks;

use App\Containers\AppSection\File\Data\Repositories\FileRepository;
use App\Ship\Exceptions\CreateResourceFailedException;
use App\Ship\Parents\Tasks\Task;
use Exception;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class CreateFileTask extends Task
{
    protected FileRepository $repository;
    protected Storage $storage;

    public function __construct(
        FileRepository $repository,
        Storage        $storage
    )
    {
        $this->storage = $storage;
        $this->repository = $repository;
    }

    public function run(UploadedFile $file, string $fileType, int $profileId, int $projectId = null)
    {
        try {
            $dir = config('filesystems.disks.' . config('filesystems.cloud') . '.dir');
            $path = $this->storage::disk(config('filesystems.cloud'))->put($dir . '/' . Auth::id(), $file);

            return $this->repository->create([
                'user_id' => Auth::id(),
                'profile_id' => $profileId,
                'project_id' => $projectId,
                'name' => pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME),
                'path' => $path,
                'extension' => $file->getClientOriginalExtension(),
                'size' => $file->getSize(),
                'type' => $fileType
            ]);

        } catch (Exception $exception) {
            throw new CreateResourceFailedException();
        }
    }
}
